import Singleton from "../../framework/scripts/base/Singleton"
import Constants from "../Constants"
import DataMgr from "../manager/DataMgr"
import NetMgr from "../net/NetMgr"
import Packet from "../net/Packet"
import AccountLogin from "../pb/AccountLogin"
import AccountRoleCreate from "../pb/AccountRoleCreate"
import AccountRoleCreateOk from "../pb/AccountRoleCreateOk"
import AccountRoleLogin from "../pb/AccountRoleLogin"
import AccountRoles from "../pb/AccountRoles"
import AccountRolesOk from "../pb/AccountRolesOk"
import RoleLoginOk from "../pb/RoleLoginOk"
import Util from "../util/Util"


export default class AccountCtrl extends Singleton {
    public static get inst() {
        return this.getInstance<AccountCtrl>()
    }


    public onNetOpen() {
        // 如果登录了角色直接登录角色，否则先登录再请求角色列表
        this.netLogin()
    }


    private netLogin() {
        const loginReq = new AccountLogin(DataMgr.inst.account, 0, '')
        NetMgr.inst.sendCall(loginReq.encode(), (packet: Packet) => {
            console.log('登录成功')
            this.netRoles()
        })
    }

    private netRoles() {
        const rolesReq = new AccountRoles(Constants.sid)
        NetMgr.inst.sendCall(rolesReq.encode(), (packet: Packet) => {
            const rolesOk = AccountRolesOk.decode(packet)
            console.log('获取角色列表成功 rolesOk:', rolesOk)
            if (rolesOk.roles.length <= 0) {
                this.netCreate()
            } else {
                const rid = rolesOk.roles[0].rid
                this.netRoleLogin(rid)
            }
        })
    }

    private netCreate() {
        const createReq = new AccountRoleCreate(Constants.sid, 1, Util.randChars(6))
        NetMgr.inst.sendCall(createReq.encode(), (packet: Packet) => {
            const createOk = AccountRoleCreateOk.decode(packet)
            console.log('创建角色成功 id:' + createOk.rid + ' 准备登录')
            this.netRoleLogin(createOk.rid)
        })
    }

    private netRoleLogin(rid: Long) {
        console.log('角色登录')
        const roleLoginReq = new AccountRoleLogin(rid, '')
        NetMgr.inst.sendCall(roleLoginReq.encode(), (packet: Packet) => {
            const roleLoginOk = RoleLoginOk.decode(packet)
            console.log('角色登录成功:', roleLoginOk)

        })
    }
}
